﻿// Matt's TinyMVC Copyright (c) 2009 Matt J. Crouch

// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the "Software"), to deal in the Software without restriction, 
// including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, 
// and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, 
// subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all copies
// or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN 
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MattsTinyMVC.Properties;

namespace MattsTinyMVC
{
    public abstract class BaseViewPage : Page
    {
        private Type _controllerType;
        private Type _cacheType;
        private Dictionary<string, Control> _controlLocator;
        private IControllerCache _cache;
        private string _controllerCacheKey = string.Empty;

        public BaseController Controller { get; private set; }

        protected BaseViewPage(Type controllerType, Type cacheType)
        {
            _controllerType = controllerType;
            _controlLocator = new Dictionary<string, Control>();
            _cacheType = cacheType;
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            _controllerCacheKey = Page.ToString() + Session.SessionID;
            GetController();
            Controller.RefreshModelLocator(!IsPostBack);
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            Page.DataBind();
            UpdateModels();
            _cache.Set(_controllerCacheKey, Controller);
        }

        protected void ExecuteCommand(object sender, EventArgs e)
        {
            IAttributeAccessor control = sender as IAttributeAccessor;
            Controller.DispatchCommand(control.GetAttribute("ModelCommandName"), int.Parse(control.GetAttribute("ModelID"), CultureInfo.CurrentCulture));
            Page.DataBind();
        }

        protected void RegisterForUpdate(object sender, EventArgs e)
        {
            Control controlToRegister = sender as Control;

            if (!_controlLocator.ContainsKey(controlToRegister.UniqueID))
                _controlLocator.Add(controlToRegister.UniqueID, controlToRegister);
        }

        private void GetController()
        {
            if (_cacheType != null)
                _cache = Activator.CreateInstance(_cacheType) as IControllerCache;
            else
                _cache = new SessionCache(Session);

            Controller = _cache.Get(_controllerCacheKey);
            if (Controller == null)
            {
                if (!IsPostBack)
                {
                    Controller = Activator.CreateInstance(_controllerType) as BaseController;
                    _cache.Add(_controllerCacheKey, Controller);
                }
                else
                    throw new HttpException(Resources.ControllerExpired);
            }
            Controller.ControllerState = HttpContext.Current;
        }

        private void UpdateModels()
        {
            if (!IsPostBack)
                return;
            
            foreach (Control control in _controlLocator.Values)
            {
                IAttributeAccessor controlAttributes = control as IAttributeAccessor;
                if (controlAttributes == null)
                    continue;

                WebControl webControl = control as WebControl;
                if(webControl != null && !webControl.Enabled)
                    continue;

                string modelIDAttribute = controlAttributes.GetAttribute("ModelID");
                string modelPropertyNameAttribute = controlAttributes.GetAttribute("ModelPropertyName");
                if (string.IsNullOrEmpty(modelIDAttribute) || string.IsNullOrEmpty(modelPropertyNameAttribute))
                    continue;

                int modelID;
                if(!int.TryParse(modelIDAttribute, out modelID))
                    throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.InvalidModelIDSpecified, modelID));
                
                if (!Controller.ModelLocator.ContainsKey(modelID))
                    throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.ModelNotFound, modelID)); 

                object model = Controller.ModelLocator[modelID];
                PropertyInfo modelProperty = model.GetType().GetProperty(modelPropertyNameAttribute);

                object newModelPropertyValue = null;
                string postedBackModelPropertyValue = Request.Form[control.UniqueID];
                if (postedBackModelPropertyValue == null)
                    continue;

                try
                {
                    if (modelProperty.PropertyType.IsEnum)
                        newModelPropertyValue = Enum.Parse(modelProperty.PropertyType, postedBackModelPropertyValue);
                    else
                        newModelPropertyValue = Convert.ChangeType(postedBackModelPropertyValue, modelProperty.PropertyType, CultureInfo.CurrentCulture);

                    modelProperty.SetValue(model, newModelPropertyValue, null);
                }
                catch (Exception e)
                {
                    throw new ArgumentException(Resources.CannotSetModelProperty, e);
                }
            }
        }
    }
}
